package com.ligotop.admin.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author: yudm
 * @date: 2017-09-19 14:40
 */
@Aspect
@Component
public class WebLogAspect {

    private Logger logger =  LoggerFactory.getLogger(this.getClass());

    ThreadLocal<Long> startTime = new ThreadLocal<>();
    ThreadLocal<Map<String,Object>> params = new ThreadLocal<>();

    /**
     * 定义一个切入点.
     * 解释下：
     *
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 任意包名
     * ~ 第三个 * 代表任意方法.
     * ~ 第四个 * 定义在web包或者子包
     * ~ 第五个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
//    @Pointcut("execution(public * com.kfit.*.web..*.*(..))")
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        Map<String,Object> paramsMap = new HashMap<>();
        try {
            startTime.set(System.currentTimeMillis());
            // 接收到请求，记录请求内容
//        logger.info("WebLogAspect.doBefore()");
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();


            paramsMap.put("URL", request.getRequestURL().toString());
            paramsMap.put("HTTP_METHOD", request.getMethod());
            paramsMap.put("IP", request.getMethod());
            paramsMap.put("CLASS_METHOD", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            paramsMap.put("ARGS", Arrays.toString(joinPoint.getArgs()));
            // 记录下请求内容
            //获取所有参数方法一：
            Map<String,String> reqParam = new HashMap<>();
            Enumeration<String> enu=request.getParameterNames();
            while(enu.hasMoreElements()){
                String paraName=enu.nextElement();
                reqParam.put(paraName,request.getParameter(paraName));
            }
            paramsMap.put("REQUEST_PARAMS",reqParam);
        }catch (Exception e){
            logger.error("日志记录出错！");
            e.printStackTrace();
        }
        params.set(paramsMap);
    }

    @AfterReturning("webLog()")
    public void  doAfterReturning(JoinPoint joinPoint){
        // 处理完请求，返回内容
        Map map = params.get();
        try {
            map.put("TIME_CONSUMING",System.currentTimeMillis() - startTime.get());
        }catch (Exception e){
            e.printStackTrace();
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            logger.info(objectMapper.writeValueAsString(map));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
